﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using HtmlAgilityPack;
using Soufun.DAL;
using Soufun.DB;
using Soufun.Model;
using System.Drawing;

namespace Soufun
{
    public partial class ProjectDetailAnalysisForm : DevExpress.XtraEditors.XtraForm
    {

        private List<ProjectDetailInfo> projectDetailInfos = new List<ProjectDetailInfo>();
        public readonly Hashtable CompareResultList = Hashtable.Synchronized(new Hashtable());
        public readonly Hashtable HouseTypeList = Hashtable.Synchronized(new Hashtable());
        private string _strTablePath =
    "//html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[2]/table[1]" +
    "/tbody[1]/tr[2]/td[1]/table[2]/tbody[1]/tr[1]/td[1]/table[1]" +
    "/tbody[1]/tr[2]/td[1]/table[1]/tr[2]/td[1]//table[3]/tr[1]" +
    "/td[1]/table[1]/tbody[1]/tr";
        private string _strTdPath = "//td";
        private DProjectUrl _dProjectUrl = new DProjectUrl();
        private DProjectDetail _dProjectDetail = new DProjectDetail();
        private DProjectArea _dProjectArea = new DProjectArea();
        private DHouseType _dHouseType = new DHouseType();
        private bool _isCatchAll;
        private int _totalRows = 0;
        private int _succeedRows = 0;
        private DateTime _insetTime;
        private bool _isStatisticsAll;




        public ProjectDetailAnalysisForm()
        {
            InitializeComponent();
        }

        private void LoadProjectUrlList()
        {
            try
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    comboBox_projectList.Properties.Items.Clear();
                    ImageComboBoxItem item = new ImageComboBoxItem();
                    item.Description = "所有项目";
                    item.Value = "所有项目";
                    item.ImageIndex = 0;
                    comboBox_projectList.Properties.Items.Add(item);

                }));
                DataSet ds = _dProjectUrl.GetList("");
                if (ds == null || ds.Tables.Count == 0)
                {
                    XtraMessageBox.Show("未能加载项目web列表，请检查数据库连接是否正常！");
                    return;
                }
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string projectName = row["ProjectName"].ToString();
                    string projecturl = row["ProjectUrl"].ToString();
                    ImageComboBoxItem item = new ImageComboBoxItem();
                    item.Description = projectName;
                    item.Value = projecturl;
                    item.ImageIndex = int.Parse(row["Id"].ToString());
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        comboBox_projectList.Properties.Items.Add(item);
                    }));
                }
            }
            catch (Exception ex)
            {
                
                throw;
            }
           
     
        }


        private void btn_catchData_MouseClick(object sender, MouseEventArgs e)
        {
          
            if (comboBox_projectList.SelectedIndex<0)
            {
                XtraMessageBox.Show("请选择想要抓取数据的项目！");
                return;
            }

            if (XtraMessageBox.Show("确定抓取数据？", "提醒：",
             MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            comboBox_projectList.Enabled = false;
            btn_catchAll.Enabled = false;
            btn_catchData.Enabled = false;
            marqueeProgressBarControl1.Visible = true;
            marqueeProgressBarControl1.Text = "开始从网页中抓取数据...";
            marqueeProgressBarControl1.Properties.Stopped = false;

            Thread t = new Thread(GetSelectedProjectDetailData) 
            { IsBackground = true };
            t.Start();             
        }

        private void btn_catchAll_MouseClick(object sender, MouseEventArgs e)
        {
            if (comboBox_projectList.Properties.Items.Count==0)
            {
                XtraMessageBox.Show("当前数据库中尚未添加项目！");
                return;
            }
            if (XtraMessageBox.Show("确定抓取数据？", "提醒：",
             MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }
            btn_addProject.Enabled = false;
            btn_deleteProject.Enabled = false;
            btn_catchAll.Enabled = false;
            btn_catchData.Enabled = false;
            marqueeProgressBarControl1.Visible = true;
            marqueeProgressBarControl1.Text = "开始从网页中抓取数据...";
            marqueeProgressBarControl1.Properties.Stopped = false;
            _isCatchAll = true;
            _totalRows = 0;
            _succeedRows = 0;

            Thread t = new Thread(GetAllProjectDetailData) { IsBackground = true };
            t.Start();     
        }

     
        private void GetAllProjectDetailData()
        {
            _insetTime = DateTime.Now;

            for (int i = 0; i < comboBox_projectList.Properties.Items.Count; i++)
            {
                BeginInvoke(new MethodInvoker(()
                                =>
                {
                    marqueeProgressBarControl1.Text = "开始抓取第"+(i+1)
                       +"/"+comboBox_projectList.Properties.Items.Count
                       +"个项目的数据...";
                }));
               
                AnalysisHtmlStringToProjectDetailInfo(i);    
            }
            BeginInvoke(new MethodInvoker(()
                                   =>
                {
                    string strShow = "所有数据抓取完毕！共" +
                    _totalRows + "条数据!";
                    if (_totalRows != _succeedRows)
                    {
                        strShow += "失败" + (_totalRows - _succeedRows) + "条！";
                    }
                    marqueeProgressBarControl1.Text = strShow;
                    marqueeProgressBarControl1.Properties.Stopped = true;
                    comboBox_projectList.Enabled = true;
                    btn_catchData.Enabled = true;
                    btn_catchAll.Enabled = true;
                    btn_addProject.Enabled = true;
                    btn_deleteProject.Enabled = true;
                }));
        }
         
        private void GetSelectedProjectDetailData()
        {                               
            AnalysisHtmlStringToProjectDetailInfo(comboBox_projectList.SelectedIndex);
        }

        private void AnalysisHtmlStringToProjectDetailInfo(int index)
        {
            projectDetailInfos.Clear();
            try
            {
                string strNotice = "";
                if (_isCatchAll)
                {
                    strNotice = "第" + (index + 1) + "/" +
                        comboBox_projectList.Properties.Items.Count
                        + "个项目";
                }
                string url = comboBox_projectList.Properties.Items[index].Value.ToString();
                string httpText = Common.GetHtmlTextByUrl(url);

                BeginInvoke(new MethodInvoker(() =>
                    marqueeProgressBarControl1.Text = strNotice +
                    "数据抓取完毕，开始解析数据..."))
                ;
                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(httpText);
                HtmlNode rootNode = document.DocumentNode;
                HtmlNodeCollection categoryNodeList = rootNode.SelectNodes(_strTablePath);
                if (categoryNodeList == null)
                {
                    return;
                }
                //---前面两行数据无效
                for (int i = 3; i < categoryNodeList.Count; i++)
                {

                    ProjectDetailInfo projectDetailInfo = new ProjectDetailInfo();

                    int projectId = comboBox_projectList.Properties.Items[index].ImageIndex;
                    projectDetailInfo.ProjectId = projectId;

                    HtmlNode trNode = HtmlNode.CreateNode(categoryNodeList[i].OuterHtml);
                    HtmlNodeCollection tdNodes = trNode.SelectNodes(_strTdPath);
                    #region  HTML标签
                    //<td>1</td>
                    //<td>1</td>
                    //<td>3</td>
                    //<td bgcolor="#CCFFFF"><font title='房型：32'>1</font></td>
                    //<td bgcolor="#CCFFFF"><font title='房型：22'>2</font></td>
                    //<td bgcolor="#CCFFFF"><font title='房型：22'>3</font></td>
                    //<td bgcolor="#FFFF00">4</td>
                    //<td bgcolor="#FFFF00">5</td>
                    //<td bgcolor="#FFFF00">6</td>
                    #endregion

                    //-------栋号
                    HtmlNode tdNodeBuilding = HtmlNode.CreateNode(tdNodes[0].OuterHtml);
                    projectDetailInfo.BuildingID = tdNodeBuilding.InnerText;
                    //-------单元，所以单元号有可能为 "/"这种情况认为是0单元。
                    HtmlNode tdNodeUnit = HtmlNode.CreateNode(tdNodes[1].OuterHtml);
                    projectDetailInfo.UnitID = tdNodeUnit.InnerText;

                    //-------层数
                    HtmlNode tdNodeFloor = HtmlNode.CreateNode(tdNodes[2].OuterHtml);
                    projectDetailInfo.FloorID = tdNodeFloor.InnerText;

                    projectDetailInfo.HouseAttribute = string.Empty;
                    //----下面是个房间的号码和对应的属性。
                    for (int ii = 3; ii < tdNodes.Count; ii++)
                    {
                        HtmlNode tdNodeii = HtmlNode.CreateNode(tdNodes[ii].OuterHtml);

                        //-------------------------------------------houseId可能是1、301、2001、（1）、风井、-   。这样的东西
                        string houseID = tdNodeii.InnerText;
                        houseID = houseID.Replace("(", "");
                        houseID = houseID.Replace(")", "");

                        int tmphouseID;
                        if (!int.TryParse(houseID, out tmphouseID))
                        {
                            //----            -1表示该房间无用
                            projectDetailInfo.HouseAttribute += "-1,";
                        }
                        else
                        {
                            string houseAttributes = tdNodeii.Attributes[0].Value;
                            int houseAttributesID = HouseAttributesColorStringToInt(houseAttributes);
                            Console.WriteLine("houseID :" + houseID + "," + "houseAttributesID :" + houseAttributesID.ToString());
                            //---------------------索引表示是第几个房间，Vaule是表示该房间的当前属性；
                            projectDetailInfo.HouseAttribute += houseAttributesID + ",";
                        }

                    }

                    projectDetailInfos.Add(projectDetailInfo);
                }

                if (projectDetailInfos.Count > 0)
                {
                    _totalRows += projectDetailInfos.Count;

                    BeginInvoke(new MethodInvoker(() =>
                    marqueeProgressBarControl1.Text = strNotice +
                    "解析完毕,正在保存到数据库..."));
                    Console.WriteLine("正在保存数据到本地");
                    if (!_isCatchAll)
                    {
                        _insetTime = DateTime.Now;
                    }
                    int succeedrows = 0;
                    int insertRowsCount = 500;
                    StringBuilder strSql = new StringBuilder();
                    for (int i = 0; i < projectDetailInfos.Count; i++)
                    {
                        ProjectDetailInfo projectInfo = projectDetailInfos[i];
                        if (i % insertRowsCount == 0)
                        {
                            strSql = new StringBuilder();
                            // strSql.Append("set names  'uft8';");
                            strSql.Append("Insert into tprojectdetailinfo (");
                            strSql.Append("ProjectId,BuildingID,UnitID,");
                            strSql.Append("FloorID,HouseAttribute,InsertTime)");
                            strSql.Append(" value  ");
                        }
                        strSql.Append("(");
                        strSql.Append(projectInfo.ProjectId);
                        strSql.Append(",'");
                        strSql.Append(projectInfo.BuildingID);
                        strSql.Append("','");
                        strSql.Append(projectInfo.UnitID);
                        strSql.Append("','");
                        strSql.Append(projectInfo.FloorID);
                        strSql.Append("','");
                        strSql.Append(projectInfo.HouseAttribute);
                        strSql.Append("','");
                        strSql.Append(_insetTime);
                        strSql.Append("'),");
                        if ((i + 1) % insertRowsCount == 0 ||
                            i == projectDetailInfos.Count - 1)
                        {
                            strSql.Remove(strSql.Length - 1, 1);
                            int succeed = DbHelper.ExecuteSql(strSql.ToString());
                            succeedrows += succeed;
                            _succeedRows += succeed;
                        }
                    }


                    BeginInvoke(new MethodInvoker(()
                                         =>
                    {
                        if (succeedrows == projectDetailInfos.Count)
                        {
                            marqueeProgressBarControl1.Text = strNotice
                                + "数据抓取、保存成功！";
                            ImageComboBoxItem item = new ImageComboBoxItem();
                            item.Description = _insetTime.ToString("yyyy/M/d HH:mm:ss");
                            item.Value = _insetTime;
                            if (!_isCatchAll)
                            {
                                comboBox_startTime.Properties.Items.Insert(0, item);
                                comboBox_endTime.Properties.Items.Insert(0, item);
                            }
                        }
                        else
                        {
                            int failedCount = projectDetailInfos.Count - succeedrows;
                            marqueeProgressBarControl1.Text = failedCount + "条数据保存失败！请检测数据库连接是否正常";
                        }
                        if (!_isCatchAll)
                        {
                            marqueeProgressBarControl1.Properties.Stopped = true;
                            comboBox_projectList.Enabled = true;
                            btn_catchData.Enabled = true;
                            btn_catchAll.Enabled = true;
                        }

                    }));
                }
            }
            catch (Exception ex)
            {
                 //XtraMessageBox.Show("")
            }

          
        }

         
        private string GetStateByIntValue(string intValue)
        {
            string strValue = "";
            switch (intValue)
            {
                case "0":
                    strValue = "未销（预）售";
                    break;
                case "1":
                    strValue = "已网上销售";
                    break;
                case "2":
                    strValue = "已办证";
                    break;
                case "3":
                    strValue = "限制出售";
                    break;
                case "4":
                    strValue = "已抵押";
                    break;
                case "5":
                    strValue = "已查封";
                    break;
            }
            return strValue;
        }

        private int HouseAttributesColorStringToInt(string colorString)
        {

            // 已网上销售：bgcolor="#FF0000"     ------------------  1表示
            //未销（预）售：   bgcolor="#CCFFFF" ------------------  0表示
            //已办证： bgcolor="#00FF00"            ------------------- 2表示
            //限制出售：bgcolor="#000000"          ------------------- 3表示
            //已抵押： bgcolor="#FFFF00"            -------------------  4表示
            //已查封：bgcolor="#CC0099"            -------------------  5表示
            //已抵押已查封：bgcolor="#FFFF00"  带个*号，暂时认为和已抵押是一样的。 --------3表示
            switch (colorString)
            {
                case "#CCFFFF":
                    return 0;
                    break;
                case "#FF0000":
                    return 1;
                    break;
                case "#00FF00":
                    return 2;
                    break;
                case "#FFFF00":
                    return 3;
                    break;
                case "#CC0099":
                    return 4;
                    break;
                default:
                    return -1;
                    break;
            }
        }

      

        private void ComparePrejectData(ProjectNameIdInfo info,
            DataTable dataTableFrist, DataTable dataTableSecond,
            DataTable dataTableArea)
        {

            for (int i = 0; i < dataTableFrist.Rows.Count; i++)
            {
                if (dataTableSecond.Rows.Count<dataTableFrist.Rows.Count)
                {
                    break;
                }
                if (dataTableArea.Rows.Count<dataTableFrist.Rows.Count)
                {
                    XtraMessageBox.Show("项目【" + info.Name + "】没有对应的面积表！");
                    break;                   
                }
                //最后一列存的是属性的string，like 。1,2,3,4,5,6,
                string compareString1 = dataTableFrist.Rows[i]["HouseAttribute"].ToString();
                string compareString2 = dataTableSecond.Rows[i]["HouseAttribute"].ToString();
                string areaString = dataTableArea.Rows[i]["ProjectAreaString"].ToString();

                string projectId = dataTableSecond.Rows[i]["ProjectId"].ToString();
                string unitID = dataTableArea.Rows[i]["UnitID"].ToString();
                
                if (compareString1 != compareString2)
                {
                    //-------这三个数组的长度要是一样的。
                    string[] compareStringArray1 = compareString1.Split(',');
                    string[] compareStringArray2 = compareString2.Split(',');
                    string[] areaStringArray = areaString.Split(',');

                    for (int j = 0; j < compareStringArray1.Length; j++)
                    {
                        if (compareStringArray1[j] != compareStringArray2[j]
                            && compareStringArray1[j] != "-1"
                             && compareStringArray2[j] != "-1"
                             && compareStringArray1[j] != ""
                             && compareStringArray2[j] != ""
                            && areaStringArray[j] != "0")
                        {
                            string key =  info.Name+"|"+
                                compareStringArray1[j] + "|" 
                                + compareStringArray2[j] + "|" + areaStringArray[j];

                            int houseId = j + 1;
                            HouseTypeList[key] = projectId + "|" + unitID + "|" + areaStringArray[j];

                            if (!CompareResultList.ContainsKey(key))
                            {
                                CompareResultList[key] = 1;
                            }
                            else
                            {
                                CompareResultList[key] = int.Parse(CompareResultList[key].ToString()) + 1;
                            }
                        }
                    }
                     
                }
            }

           
        }

        private void BindResult()
        {
            BeginInvoke(new MethodInvoker(() =>
                {
                    gridControl1.DataSource = _dt1;
                    gridControl2.DataSource = _dt2;
                    gridControl3.DataSource = _dt3;
                    gridView1.GroupPanelText = DateTime.Parse(
                        comboBox_startTime.SelectedItem.ToString()
                        ).ToString("yy年MM月dd号HH点mm分抓取数据");
                    gridView2.GroupPanelText = DateTime.Parse(
                        comboBox_endTime.SelectedItem.ToString()
                        ).ToString("yy年MM月dd号HH点mm分抓取数据");
                    gridView3.GroupPanelText = "项目面积信息";        
                }));
             
            DataTable dt = new DataTable();
            dt.Columns.Add("ProjectName");
            dt.Columns.Add("OldState");
            dt.Columns.Add("NewState");
            dt.Columns.Add("Area");
            dt.Columns.Add("Count");
            dt.Columns.Add("HouseType");

            foreach (DictionaryEntry dictionaryEntry in CompareResultList)
            {
                string key = dictionaryEntry.Key.ToString();//projectName ,s1,s2,area
                string ketType = HouseTypeList[key].ToString();
                string[] typeArray = ketType.Split('|'); // 1.projectId  2.unitID 3.area
                string houseType = _dHouseType.GetHouseType(
                    int.Parse(typeArray[0]),
                    double.Parse(typeArray[2]));

                string[] keyArray = key.Split('|');
                DataRow row = dt.NewRow();
                row["ProjectName"] = keyArray[0];
                row["OldState"] = GetStateByIntValue(keyArray[1]);
                row["NewState"] = GetStateByIntValue(keyArray[2]);
                row["Area"] = keyArray[3];
                row["Count"] = CompareResultList[key];
                row["HouseType"] = houseType;
                dt.Rows.Add(row);
                Console.WriteLine(key + "count:" + CompareResultList[key]);
            }

            DataView dv = dt.DefaultView;
            dv.Sort = "ProjectName";
            BeginInvoke(new MethodInvoker(() =>
                {
                    gridControl4.DataSource = dv;
                    comboBox_projectList.Enabled = true;
                    comboBox_startTime.Enabled = true;
                    comboBox_endTime.Enabled = true;
                    btn_select.Enabled = true;
                    btn_addProject.Enabled = true;
                    btn_deleteProject.Enabled = true;
                }));
        }


        private void comboBox_projectList_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox_startTime.Properties.Items.Clear();
            comboBox_endTime.Properties.Items.Clear();

            gridControl1.DataSource = null;
            gridControl2.DataSource = null;
            gridControl3.DataSource = null;
            gridControl4.DataSource = null;

            if (comboBox_projectList.SelectedIndex == -1)
            {
                return;
            }
            label_url.Text = comboBox_projectList.Properties.Items[
                comboBox_projectList.SelectedIndex].Value.ToString();
            comboBox_projectList.Enabled = false;
            Thread t = new Thread(BindInsertTimeList) { IsBackground = true };
            t.Start();
        }

        private void BindInsertTimeList()
        {
            DataSet ds;
            if (comboBox_projectList.SelectedIndex==0)
            {
                ds = _dProjectDetail.GetAllInsetTimeList();
            }
            else
            {
                int projectId = comboBox_projectList.Properties.Items[
                    comboBox_projectList.SelectedIndex].ImageIndex;
                ds = _dProjectDetail.GetInsetTimeList(projectId);    
            }            
            if (ds==null ||ds.Tables.Count==0)
            {
                XtraMessageBox.Show("加载抓取数据时间列表异常，请检查数据库连接是否正常！");
                return;
            }
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string insertTime = row["InsertTime"].ToString();
                BeginInvoke(new MethodInvoker(() =>
                    {
                        ImageComboBoxItem item = new ImageComboBoxItem();
                        item.Description= insertTime;
                        item.Value=insertTime;
                        comboBox_startTime.Properties.Items.Add(item);
                        comboBox_endTime.Properties.Items.Add(item);
                    }));
            }
            BeginInvoke(new MethodInvoker(() =>
            {
                comboBox_projectList.Enabled = true;
                comboBox_startTime.Enabled = true;
                comboBox_endTime.Enabled = true;
            }));
        }

        private void btn_select_MouseClick(object sender, MouseEventArgs e)
        {
            if (!CheckSelectedvalue()) return;           
            gridControl1.DataSource = null;
            gridControl2.DataSource = null;
            gridControl3.DataSource = null;
            gridControl4.DataSource = null;
            comboBox_projectList.Enabled = false;
            comboBox_startTime.Enabled = false;
            comboBox_endTime.Enabled = false;
            btn_select.Enabled = false;
            btn_addProject.Enabled = false;
            btn_deleteProject.Enabled = false;
            if (_dt1!=null)
            {
                _dt1.Rows.Clear();    
            }
            if (_dt2!=null)
            {
                _dt2.Rows.Clear();    
            }
            if (_dt3!=null)
            {
                _dt3.Rows.Clear();
            }
            CompareResultList.Clear();
            HouseTypeList.Clear();


            if (comboBox_projectList.SelectedIndex==0)
            {
                _isStatisticsAll = true;
                lb_notice.Visible = true;
                Thread t = new Thread(GetAllResutl) { IsBackground = true };
                t.Start();
            }
            else
            {
                _isStatisticsAll = false;
                ProjectNameIdInfo info = new ProjectNameIdInfo();
                info.Id = comboBox_projectList.Properties.Items[
                comboBox_projectList.SelectedIndex].ImageIndex;
                info.Name = comboBox_projectList.Properties.Items[
                    comboBox_projectList.SelectedIndex].Description;
                Thread t = new Thread(GetResult){IsBackground = true};
                t.Start(info);
            }            
        }

        private DataTable _dt1;
        private DataTable _dt2;
        private DataTable _dt3;

        private void GetResult(object objNameIdInfo)
        {
            ProjectNameIdInfo info = (ProjectNameIdInfo) objNameIdInfo;
            DateTime startTime = DateTime.Parse(comboBox_startTime.SelectedItem.ToString());
            DateTime endTime = DateTime.Parse(comboBox_endTime.SelectedItem.ToString());
            DataSet ds1 = _dProjectDetail.GetList("InsertTime ='" + startTime + "' and ProjectId=" + info.Id);
            DataSet ds2 = _dProjectDetail.GetList("InsertTime ='" + endTime + "' and ProjectId=" + info.Id);
            DataSet ds3 = _dProjectArea.GetList("ProjectId=" + info.Id);
            if (ds1 == null || ds1.Tables.Count == 0 ||
                ds2 == null || ds2.Tables.Count == 0 ||
                ds3 == null || ds3.Tables.Count == 0)
            {
                XtraMessageBox.Show("未找到相关数据，请检查数据库连接是否正常已经相关数据是否存在！");
                return;
            }
            if ((_dt1==null||_dt1.Rows.Count==0)&&
                (_dt2==null||_dt2.Rows.Count==0)&&
                (_dt3==null||_dt3.Rows.Count==0))
            {
                _dt1 = ds1.Tables[0].Copy();
                _dt2 = ds2.Tables[0].Copy();
                _dt3 = ds3.Tables[0].Copy();
            }
            else
            {
                foreach (DataRow row in ds1.Tables[0].Rows)
                {
                    _dt1.Rows.Add(row.ItemArray);
                }
                foreach (DataRow row in ds2.Tables[0].Rows)
                {
                    _dt2.Rows.Add(row.ItemArray);
                }
                foreach (DataRow row in ds3.Tables[0].Rows)
                {
                    _dt3.Rows.Add(row.ItemArray);
                }
            }        
            ComparePrejectData(info,
            ds1.Tables[0], ds2.Tables[0], ds3.Tables[0]);
            if (!_isStatisticsAll)
            {
                BindResult();
            }
                
        }

        private void GetAllResutl()
        {
            
            for (int i = 1; i < comboBox_projectList.Properties.Items.Count; i++)
            {
                ProjectNameIdInfo info = new ProjectNameIdInfo();
                info.Id = comboBox_projectList.Properties.Items[
                i].ImageIndex;
                info.Name = comboBox_projectList.Properties.Items[
                    i].Description;
                GetResult(info);
                BeginInvoke(new MethodInvoker(() => 
                lb_notice.Text="完成进度："+i+"/"+
                (comboBox_projectList.Properties.Items.Count)
                ));
            }
            BindResult();
            XtraMessageBox.Show("完成统计！");
        }
         
        private void btn_addProject_Click_1(object sender, EventArgs e)
        { 
            AddProjectInfo addProjectInfo = new AddProjectInfo();
            addProjectInfo.ShowDialog();

            Thread t = new Thread(LoadProjectUrlList){IsBackground = true};
            t.Start();
        }

        private void btn_deleteProject_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("确定删除该项目？", "警告：", MessageBoxButtons.YesNo)
                == DialogResult.No)
            {
                return;
            }
            comboBox_projectList.Enabled = false;
            btn_catchData.Enabled = false;
            marqueeProgressBarControl1.Visible = false;
            btn_select.Enabled = false;
            Thread t = new Thread(DeleteProject) { IsBackground = true };
            t.Start();
        }

        private void DeleteProject()
        {
            int projectId = comboBox_projectList.Properties.Items[
              comboBox_projectList.SelectedIndex].ImageIndex;
            try
            {
                int rUrl = _dProjectUrl.DeleteById(projectId);
                int rArea = _dProjectArea.DeleteByProjectId(projectId);
                int rDetail = _dProjectDetail.DeleteByProjectId(projectId);
                int rHouseType = _dHouseType.Delete(projectId);
                if (rUrl > 0)
                {
                    XtraMessageBox.Show("删除成功！");
                    BeginInvoke(new MethodInvoker(() =>
                        {
                            label_url.Text = "";
                        }));
                    LoadProjectUrlList();
                }
                else
                {
                    XtraMessageBox.Show("删除失败，请确认该项目是否存在!");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("删除失败，原因：" + ex.Message);
            }
            BeginInvoke(new MethodInvoker(() =>
                {
                    comboBox_projectList.SelectedIndex = -1;
                    comboBox_projectList.Enabled = true;
                    btn_catchData.Enabled = true;
                    btn_select.Enabled = true;
                }));

        }

        private bool CheckSelectedvalue()
        {
            if (comboBox_projectList.SelectedIndex < 0)
            {
                XtraMessageBox.Show("请选择想要查看的项目！");
                comboBox_projectList.Focus();
                return false;
            }
            if (comboBox_startTime.SelectedIndex < 0)
            {
                XtraMessageBox.Show("请选择第一个抓取时间！");
                comboBox_startTime.Focus();
                return false;
            }
            if (comboBox_endTime.SelectedIndex < 0)
            {
                XtraMessageBox.Show("请选择第二个抓取时间！");
                comboBox_endTime.Focus();
                return false;
            }
            if (DateTime.Parse(comboBox_startTime.SelectedItem.ToString()) >=
                DateTime.Parse(comboBox_endTime.SelectedItem.ToString()))
            {
                XtraMessageBox.Show("第一个抓取时间应比第二个抓取时间早，请重新选择！");
                comboBox_startTime.Focus();
                return false;
            }
            return true;
        }

        #region 导出Excel

        private void btn_toExcel1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                return;
            }
            string fileName = comboBox_projectList.SelectedItem+
                DateTime.Parse(comboBox_startTime.Properties.Items[
                comboBox_startTime.SelectedIndex].Description
                ).ToString("MM月dd号HH点mm");
            saveFileDialog1.FileName = fileName;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }

        private void btn_toExcel2_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                return;
            }
            string fileName = comboBox_projectList.SelectedItem +
                DateTime.Parse(comboBox_endTime.Properties.Items[
                comboBox_endTime.SelectedIndex].Description
                ).ToString("MM月dd号HH点mm");
            saveFileDialog1.FileName = fileName;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView2.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }

        private void btn_toExcel3_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                return;
            }
            string fileName = comboBox_projectList.SelectedItem +
               "面积信息";
            saveFileDialog1.FileName = fileName;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView3.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }

        private void btn_toExcel4_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right ||
                comboBox_startTime.SelectedIndex==-1 ||
                comboBox_endTime.SelectedIndex==-1)
            {
                return;
            }
            string fileName = comboBox_projectList.SelectedItem +
              DateTime.Parse(comboBox_startTime.Properties.Items[
                comboBox_startTime.SelectedIndex].Description
                ).ToString("MM月dd号HH点")+
                "至"+
                DateTime.Parse(comboBox_endTime.Properties.Items[
                comboBox_endTime.SelectedIndex].Description
                ).ToString("MM月dd号HH点"); 
            saveFileDialog1.FileName = fileName;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView4.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }
        #endregion
         
        #region 窗体效果
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.btn_exit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.btn_exitPressDown;
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.Close();
            }
        }

        #endregion

        private void ProjectDetailAnalysisForm_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(LoadProjectUrlList) { IsBackground = true };
            t.Start();
        }

        private void btn_houseTypeAreaStatistics_Click(object sender, EventArgs e)
        {
            ProjectHouseTpyeStatisticsForm form = new ProjectHouseTpyeStatisticsForm();
            form.ShowDialog();
        }

        private class ProjectNameIdInfo
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }
}